package com.hpt.search.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Title:KeywordsUtils
 * @Description:搜索关键字工具
 * @Author: zhaojunfu
 * @Date: 2015/5/28 21:22
 */
public class KeywordsUtils {
    private static String queryBoostOpt = "^";
    private static String space = " ";
    private static int factor = 50;

    /**
     * 根据搜索词的先后顺序设置权重来影响评分
     * @param keywords
     * @param multiple 倍数,即前后两个关键词之间相隔多少倍,默认1,常数50
     * @return
     */
    public static String boost(String keywords,int multiple ){
        StringBuilder result = new StringBuilder();
        //将关键字拆分
        String[] keys = keywords.split(space);
        int size = keys.length;
        int index = 0;
        int boost;
        for(String k:keys){
            boost =(int) (Math.pow(multiple,size-index-1)*factor);
            k = k+queryBoostOpt+boost;
            result.append(k);
            if(index!=(size-1)){
                result.append(space);
            }
            index++;
        }
        return result.toString();
    }

    /**
     * 使 英文+数字 的词 具有模糊查询的功能
     * @param searchKeywords
     * @return
     */
    public static String fuzzy(String searchKeywords) {
        StringBuilder re = new StringBuilder();
        String[] ks = searchKeywords.split(" ");
        int i =0;
        for(String k:ks){
            re.append(k);
            if(!isContainsChinese(k)){
                //如果不包含中文,则加上 *
                re.append("*");
            }
            if(i<ks.length-1)
                re.append(" ");
            i+=1;
        }
        return re.toString();
    }

    private static boolean isContainsChinese(String k) {
        String regEx = "[\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(k);
        boolean flg = false;
        if (matcher.find())    {
            flg = true;
        }
        return flg;
    }
}
